<template>
    <van-sticky :offset-top="44">
      <div class="header">
        <van-search v-model="queryData.title" shape="round" placeholder="请输入公司名称" @update:model-value="onSearch" />
        <div class="add" @click="addBusiness">新增</div>
      </div>
      <van-dropdown-menu active-color="#5a9df8">
        <!-- <van-dropdown-item v-model="queryData.businessStatus" :options="crmBusinessStageOption" @change="onSearch" /> -->
        <van-dropdown-item :title="createTimeTitle" ref="createTime">
          <div style="padding: 10px;">
            <div style="overflow-y: auto;height: 500px">
              <van-calendar
                :show-title="false"
                :poppable="false"
                color="#5a9df8"
                :show-confirm="false"
                :min-date="minDate"
                :default-date="defaultDate"
                type="range"
                :allow-same-day="true"
                style="height: 390px"
                @confirm="onDateConfirm"
              >
              </van-calendar>
            </div>
            <van-button round block color="#67c23a" @click="clearVisitTime"> 重置 </van-button>
          </div>
        </van-dropdown-item>
        <van-dropdown-item v-if="userInfo.isLeader == 'Y'" v-model="queryData.ownerUserId" :options="ownerUserOption"
          @change="onSearch" />
      </van-dropdown-menu>
    </van-sticky>
  
    <!-- <div class="padding-md"> -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" style="margin-top: 44px;">
      <van-list v-model="loading" :finished="finished" finished-text="" @load="onLoad">
        <div v-for="(item, index) in dataList" :key="index" class="list-wrap" @click="clickBusiness(item)">
          <div class="flex-between line">
            <div class="title van-ellipsis">{{ item.title }}</div>
            <van-tag v-if="item.businessStatusMsg" type="success" plain>{{ item.businessStatusMsg }}</van-tag>
          </div>
          <div class="flex-between-top">
            <div class="lable">单据号：</div>
            <div class="value">{{ item.sn }}</div>
          </div>
          <div class="flex-between-top">
            <div class="lable">创建日期：</div>
            <div class="value">{{ item.createTime }}</div>
          </div>
          <div class="flex-between-top">
            <div class="lable">客户名称：</div>
            <div class="value">{{ item.customerName }}</div>
          </div>
          <div class="flex-between-top">
            <div class="lable">需求数量：</div>
            <div class="value flex-end">
              <span>{{ item.expectedQuantity }}</span>
              <van-button style="margin-left: 10px;" type="primary" size="mini"
                @click.stop="toQuotation(item)">报价信息</van-button>
            </div>
          </div>
          <div class="flex-between-top">
            <div class="lable">归属人：</div>
            <div class="value">{{ item.ownerUser }}</div>
          </div>
          <!-- 成交相关 -->
          <template v-if="item.businessStatus == 'YCJ'">
            <div class="flex-between-top">
              <div class="lable">外部系统订单号：</div>
              <div class="value">{{ item.outTradeNo }}</div>
            </div>
            <div class="flex-between-top">
              <div class="lable">成单时间：</div>
              <div class="value">{{ item.signDate }}</div>
            </div>
            <div class="flex-between-top">
              <div class="lable">成单台数：</div>
              <div class="value">{{ item.quantity }}</div>
            </div>
          </template>
          <template v-if="item.businessStatus == 'YLS'">
            <!-- 流失相关 -->
            <div class="flex-between-top">
              <div class="lable">流失时间：</div>
              <div class="value">{{ item.signDate }}</div>
            </div>
            <div class="flex-between-top">
              <div class="lable">流失原因：</div>
              <div class="value">{{ item.lossReason }}</div>
            </div>
          </template>
        </div>
      </van-list>
      <van-empty v-if="!dataList.length" description="暂无数据" />
    </van-pull-refresh>
    <!-- </div> -->
  </template>
  
  <script>
  import { useStore } from 'vuex'
  import { useRouter,useRoute } from 'vue-router'
  import { getBusinessList, getUserPageList } from '@/api/businessOpportunity'
  import { getDictionary } from '@/api/dictionary'
  import { getAssetsImages } from '@/utils'
  import { reactive, toRefs, onBeforeMount, onActivated, computed, nextTick } from 'vue'
  import { ref } from 'vue'
  
  export default {
    name: 'business',
    setup(props, cxt) {
      const createTime = ref(null)
      const store = useStore()
      const router = useRouter()
      const route = useRoute()
      const getAssetsImages1 = getAssetsImages
      const userInfo = computed(() => {
        return store.getters['userInfo']
      })
      const state = reactive({
        queryData: {
          title: '',
          businessStatus: 'YCJ',
          createTimeRange: '',
          ownerUserId: '',
          current: 1,
          size: 1000
        },
        createTimeTitle: '创建日期',
        defaultDate: [new Date(), new Date()],
        minDate: new Date(2024, 0, 1),
        crmBusinessStageOption: [],
        ownerUserOption: [],
        loading: false,
        disabled: false,
        finished: false,
        refreshing: false,
        hasNextPage: false,
        total: 0,
        dataList: []
      })
      const getList = () => {
        getBusinessList(state.queryData)
          .then((res) => {
            if (state.refreshing) {
              state.dataList = []
              state.refreshing = false
            }
            const { records, total } = res
            state.hasNextPage = false
            state.dataList = records
            state.total = total
            state.finished = !state.hasNextPage
          })
          .catch(() => {
            state.refreshing = false
            state.finished = true
          })
      }
      const onSearch = () => {
        getList()
      }
  
      const onLoad = () => {
        if (state.hasNextPage) {
          state.queryData.current++
          getList()
        }
      }
      // 下拉刷新
      const onRefresh = () => {
        // 清空列表数据
        state.finished = false
        state.dataList = []
  
        // 重新加载数据
        // 将 loading 设置为 true，表示处于加载状态
        // state.loading = true
        state.queryData.current = 1
        state.hasNextPage = false
        getList()
      }
      const formatDate = (date,sigal='/') => `${date.getFullYear()}${sigal}${date.getMonth() + 1}${sigal}${date.getDate()}`
      const onDateConfirm = (values) => {
        const [start, end] = values
        state.queryData.createTimeRange = `${formatDate(start,'-')},${formatDate(end,'-')}`
        state.createTimeTitle = `${formatDate(start)} - ${formatDate(end)}`
        getList()
        setTimeout(() => {
          createTime.value.toggle()
        }, 800)
      }
      const clearVisitTime = () => {
        state.queryData.createTimeRange = ''
        state.createTimeTitle = '创建日期'
        state.defaultDate= [new Date(), new Date()]
        getList()
        createTime.value.toggle()
      }
  
      const addBusiness = () => {
        router.push({ path: './addBusiness' })
      }
  
      const clickBusiness = (item) => {
        router.push({ path: './addBusiness', query: { id: item.id } })
      }
  
      const toQuotation = (item) => {
        router.push({ path: './quotation', query: { businessId: item.id } })
      }
  
      const initDictionary = (code) => {
        getDictionary({ code }).then((res) => {
          const newDic = transOption(res)
          if (code == 'crm_business_status') {
            const first = { text: '状态', value: '' }
            newDic.unshift(first)
            state.crmBusinessStageOption = newDic
          }
        })
      }
  
      const getUserOption = () => {
        getUserPageList().then((res) => {
          const newDic = transOption(res, { value: 'realName', key: 'id' })
          const first = { text: '归属人', value: '' }
          newDic.unshift(first)
          state.ownerUserOption = newDic
        })
      }
  
      const transOption = (data, formatter = { value: 'dictValue', key: 'dictKey' }) => {
        const newDate = []
        data.map((item) => {
          const obj = {
            text: item[formatter.value],
            value: item[formatter.key]
          }
          newDate.push(obj)
        })
        return newDate
      }
  
      onBeforeMount(() => {
        //   const { salerId, status } = route.query
        //   if (status) {
        //     state.queryData.businessStatus = status
        //   }
        //   if (salerId) {
        //     state.queryData.ownerUserId = salerId
        //   }
          initDictionary('crm_business_status')
          if (userInfo.value.isLeader == 'Y') {
            getUserOption()
          } else {
              state.queryData.ownerUserId = userInfo.value.id
          }
          getList()
      })
  
      onActivated(() => {
        getList()
      })
  
      return {
        ...toRefs(state),
        userInfo,
        createTime,
        onLoad,
        onRefresh,
        addBusiness,
        onSearch,
        onDateConfirm,
        clearVisitTime,
        toQuotation,
        getAssetsImages1,
        clickBusiness
      }
    }
  }
  </script>
  <style lang="less" scoped>
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;
  
    .van-search {
      flex: 1;
      padding-right: 0;
    }
  
    .add {
      padding-left: 10px;
      padding-right: 10px;
      color: #5a9df8;
      font-size: 14px;
    }
  }
  
  .padding-md {
    padding: 0 15px 15px;
  }
  </style>
  